package com.telewave.stompdemo.clients;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.converter.StringMessageConverter;
import org.springframework.messaging.simp.stomp.*;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;

import java.lang.reflect.Type;
import java.util.concurrent.ExecutionException;

/**
 * TODO
 *
 * @author looveh
 * @since 2023/10/24 15:08:51
 **/
public class MyWebSocketClient {
    private static final Logger LOGGER = LoggerFactory.getLogger("WebSocketTest");

    public static void main(String[] args) {
        WebSocketClient webSocketClient = new StandardWebSocketClient();
        WebSocketStompClient stompClient = new WebSocketStompClient(webSocketClient);
        stompClient.setMessageConverter(new MappingJackson2MessageConverter());
        // stompClient.setTaskScheduler(null);


        String url = "ws://127.0.0.1:8080/ws";

        StompSessionHandler sessionHandler = new StompSessionHandler() {
            @Override
            public void afterConnected(StompSession session, StompHeaders connectedHeaders) {

            }

            @Override
            public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) {

            }

            @Override
            public void handleTransportError(StompSession session, Throwable exception) {

            }

            @Override
            public Type getPayloadType(StompHeaders headers) {
                return null;
            }

            @Override
            public void handleFrame(StompHeaders headers, Object payload) {
                LOGGER.info("Received : " + payload);
            }
        };

        try {
            StompSession session = stompClient.connect(url, sessionHandler).get();
            session.send("/topic/greetings", "Hello");
            session.subscribe("/topic/greetings", sessionHandler);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
